#!/usr/bin/env python

import cherrypy
from genshi.template import TemplateLoader
import os
from threading import Thread

NB_ROW_PER_PAGE = 15

class Ranking:
    
	def __init__(self, contest, mutex):
		self._contest = contest
		self._contest_mutex = mutex
		self._rankings = []
		self._slopes = []

		self._loader = TemplateLoader(
		    os.path.join(os.path.dirname(__file__), 'templates'),
		    auto_reload=True
			)
		self._current_category = None
		self._requested_category = None
    
	@cherrypy.expose
	def default(self, *category):
		self._rankings = []
		if len(category) > 0:
			self._requested_category = category[0]
			if len(category)>1:
				for word in category[1:]:
					self._requested_category = self._requested_category + ' ' + word
		else:
			self._requested_category = None
		print self._requested_category
		tmpl = self._loader.load('index.html')
		stream = tmpl.generate()
		return stream.render('html', doctype='html')

	@cherrypy.expose
	def nextpage(self):
		tmpl = self._loader.load('rankings.html')
		(climbs, slopes) = self._get_next_page()
		stream = tmpl.generate(climbers=climbs, slopes=slopes)
		return stream.render('html', doctype='html')
	
	def _get_category(self):
		categories = {}
		for climber in self._rankings:
			categories[climber[3]] = 0
		for climber in self._rankings:
			categories[climber[3]] += 1
		if self._current_category == None:
			self._current_category = categories.keys()[0]
		if not self._current_category in categories:
			for cat_id in categories:
				if categories[cat_id] > 0:
					self._current_category = cat_id
		return self._current_category
			
	
	def _get_next_climbers(self):
		climbers = []
		to_remove = []
		if len(self._rankings) == 0:
			self._rankings = self._reload_rankings()
			self._current_category = None

		if len(self._rankings) > 0:
			
			category = self._get_category()
			for climber in self._rankings:
				if climber[3] == category:
					climbers.append((
									climber[0],
									climber[2],
									climber[1],
									climber[4],
									climber[3],
				 					))
					to_remove.append(climber)
				if self._requested_category == None:
					if len(climbers) >= NB_ROW_PER_PAGE:
						break
			for climber in to_remove:
				self._rankings.remove(climber)
			return climbers

	def _get_next_slopes(self):
		slopes = []
		to_remove = []
		if len(self._slopes) == 0:
			self._contest_mutex.acquire()
			self._slopes = self._contest.get_slopes()
			self._contest_mutex.release()
		for slope in self._slopes:
			slopes.append((
							slope[0],
							slope[1],
		 					))
			to_remove.append(slope)

			if len(slopes) >= NB_ROW_PER_PAGE:
				break
		for slope in to_remove:
			self._slopes.remove(slope)
		return slopes
			
	def _get_next_page(self):
		climbers = self._get_next_climbers()
		if self._requested_category == None:
			slopes = self._get_next_slopes()
		else:
			slopes = None
		return (climbers, slopes)
		
	def _reload_rankings(self):
		self._contest_mutex.acquire()
		rankings = []
		if self._requested_category == None:
			for cat in self._contest.categories:
				for climber in self._contest.get_rankings_in_category(cat):
					rankings.append(climber)
		else:
			if self._requested_category in self._contest.categories:
				rankings = self._contest.get_rankings_in_category(self._requested_category)
		self._contest.save()
		self._contest_mutex.release()
		return rankings

class Controller(Thread):
	def __init__(self,contest, mutex):
		Thread.__init__(self)
		self._contest = contest
		self._mutex = mutex

	def launch_server(self):
		current_dir = os.path.dirname(os.path.abspath(__file__))
		conf = {
				'/': {'tools.staticdir.root': os.path.join(current_dir, 'templates')},
				'/css': {'tools.staticdir.on': True, 'tools.staticdir.dir': 'css'},
				'/js': {'tools.staticdir.on': True, 'tools.staticdir.dir': 'scripts'}
				}
		cherrypy.server.socket_port = 8000
#		cherrypy.server.socket_host = '192.168.184.54'
		cherrypy.quickstart(Ranking(self._contest, self._mutex), '/', config=conf)
		self.stop_server()
		print 'Controller stoped'

	def stop_server(self):
		cherrypy.server.stop()

	def stop(self):
		self.stop_server()
		self.join()
        
	def run(self):
		print 'Launching server'
		self.launch_server()
		
if __name__ == '__main__':
	import contest
	import threading
	contest = contest.Contest()
	contest.load_from_csv('inscriptions.csv')
#	for climber in [contest.climbers[key] for key in contest.climbers]:
#		print climber.fullname
	
	mutex = threading.Semaphore()
	ctrl = Controller(contest, mutex)
	ctrl.start()
